package org.venus.onvif.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.venus.onvif.config.Config;
import org.venus.onvif.entity.CameraJsonData;
import org.venus.onvif.entity.Video;
import org.venus.onvif.http.AjaxResult;
import org.venus.onvif.util.VideoUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

@RestController
@RequestMapping("/camera")
@CrossOrigin
public class VideoController {

    @Autowired
    private VideoUtils videoUtils;

    @PostMapping(value = "/cameraLiu")
    public AjaxResult cameraLiu(String id) {

//        zlmUtils.closeStreams("live", id);

        /*String content = readFile(fileLocation);
        System.out.println(content);
        List<Video> videoList =
                JSON.parseObject(content, new TypeReference<List<Video>>() {
                });*/
        Video video = null;
        if (Config.videos != null) {
            video = Config.videos.stream().filter(item -> item.id.equals(id)).findFirst().get();
        }

        System.out.println("预览设备:"+new Gson().toJson(video));

        JSONObject data = videoUtils.addStreamProxy("live", video.id, video.rtsp);
        CameraJsonData cameraJsonData = JSONObject.parseObject(data.toJSONString(), CameraJsonData.class);
        System.out.println("返回数据:"+new Gson().toJson(cameraJsonData));
        if (cameraJsonData.code.equals("0")) {
            String address = Config.mediaServer.ip + ":" + Config.mediaServer.port;
            String streamAddress = "ws://" + cameraJsonData.data.key
                    .replace("__defaultVhost__", address) + ".live.flv";
            return AjaxResult.success("获取成功", streamAddress);
        } else {
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 读取文件的方法
     *
     * @param fileName 要读取的文件名
     * @return 文件的内容，如果读取失败返回null
     */
    public static String readFile(String fileName) {
        try {
            // 创建一个File对象，代表我们要读取的文件
            File file = new File(fileName);

            // 使用Files工具类来读取文件的所有内容，并转化为字符串返回
            return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}